import React from 'react';
import { Space, Tag } from 'antd';
import { useSelector, useDispatch } from 'react-redux';
import { useLocation, useNavigate } from "react-router-dom"
import { closeTab, setCurrentMenu } from "../../store/reducers/tab"
import './index.css';

const CommonTag = () => {
    const tabList = useSelector((state) => state.tab.tabList);
    const currentMenu = useSelector((state) => state.tab.currentMenu);
    const dispatch = useDispatch();
    const action = useLocation();
    const navigate = useNavigate();
    const handleClose = (tag, index) => {
        let length = tabList.length - 1
        dispatch(closeTab(tag))
        //如果关闭的不是当前的Tag
        if(tag.path !== action.pathname) {
            return
        }
        if(index === length) {
            //设置当前数据
            const currentData = tabList[index -1]
            dispatch(setCurrentMenu(currentData))
            navigate(currentData.path)
        } else {
            //如果删除Tag时至少存在一个数据，则选中后一个Tag
            if(tabList.length > 1) {
                const nextData = tabList[index + 1]
                dispatch(setCurrentMenu(nextData))
                navigate(nextData.path)
            }
        }
    };

    //点击Tag
    const handleChange = (tag) => {
        dispatch(setCurrentMenu(tag))
        navigate(tag.path)
    }
    //tag显示
    const setTag = (flag, item, index) => {
        if(flag) {
            if(item.name === 'home') {
                return <Tag color="#55acee" key={item.name} onClose={() => handleClose(item, index)}>{item.label}</Tag>
            }else {
                return <Tag color="#55acee" key={item.name} onClose={() => handleClose(item, index)} closeIcon>{item.label}</Tag>
            }
        }else {
            return <Tag onClick={() => handleChange(item)} key={item.name}>{item.label}</Tag>
        }
    }
    return (
        <Space className="common-tag" size={[0,8]} wrap>
            {
                currentMenu.name && tabList.map((item, index) => (setTag(item.path === currentMenu.path, item, index)))
            }
        </Space>
    );
};

export default CommonTag;